//
//  SelectGroupViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/8.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "SelectGroupViewController.h"
#import "SelectGroupTableViewCell.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface SelectGroupViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *groupTableView; // 小组tableview
@property (nonatomic, strong) NSMutableArray *groupArray; // 小组数组
@property (nonatomic, strong) NSMutableDictionary *selectDic; // 被选中的小组

@property (nonatomic, strong) NSString *selectGroupName; // 保存选中小组的名字

@property (nonatomic, strong) UIButton *finshFenZuButton; // 完成分组按钮

@property (nonatomic, assign) BOOL canClickFenZuButton; // 是否可以点击分组button

@property (nonatomic, strong) NSMutableArray *fenZuNameArray; // 分组对应的名称
@property (nonatomic, strong) NSMutableDictionary *fenZuNameDuiYingIDDic; // 分组名称对应的ID字典

@end

@implementation SelectGroupViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    if (self.shouldGetFenZuData == YES) {
        [self shouldQingQiuFenZuData];
    } else {
        // 添加数据源
        [self addData];
    }
    
    NSLog(@"移至分组分组的名字 = %@", self.fenZuMingZiArray);
   
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"移至分组";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    if (self.shouldShowFinishButton == YES) {
        // 右方
        self.finshFenZuButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.finshFenZuButton.frame = CGRectMake(0, 0, 50, 23);
        [self.finshFenZuButton setTitle:@"完成" forState:UIControlStateNormal];
        [self.finshFenZuButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.finshFenZuButton addTarget:self action:@selector(finishFenZu:) forControlEvents:UIControlEventTouchUpInside];
        self.finshFenZuButton.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:k16Big];
        self.finshFenZuButton.layer.borderWidth = 1 * kAdjustParamater;
        self.finshFenZuButton.layer.borderColor = [[UIColor whiteColor] CGColor];
        self.finshFenZuButton.layer.cornerRadius = 6 * kAdjustParamater;
        self.finshFenZuButton.layer.masksToBounds = YES;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.finshFenZuButton];
        self.canClickFenZuButton = YES;
    }
    
   
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    self.selectGroupBlock(self.selectGroupName);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 完成分组
- (void)finishFenZu:(UIButton *)button
{
   
    if (self.canClickFenZuButton == YES) {
        self.canClickFenZuButton = NO;
        NSLog(@"完成分组");
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
        // 对应的groupID
        NSString *groupID = @"";
        if (self.shouldGetFenZuData == YES) {
            groupID = [self.fenZuNameDuiYingIDDic valueForKey:self.selectGroupName];
        } else {
            groupID = [self.fenZuMingZiDuiYingIDDic valueForKey:self.selectGroupName];
        }
        
        // 好友分组url
        NSString *changeFriendFenZuUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWChangeFriendFenZu, kCurrentUserToken];
        NSDictionary *paramaterDic = @{@"friend_group_id":groupID, @"friend_id":self.friend_id};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:changeFriendFenZuUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *statusDic = [responseObject valueForKey:@"status"];
            NSString *msgDic = [statusDic valueForKey:@"msg"];
            if ([msgDic isEqualToString:@"update success"]) {
               // [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertNoTitieWithContent:@"分组更改成功" toView:self];
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertWithAnimationByTitle:@"分组更改成功" toView:self];
                // 联系人界面需要刷新
                [[NetStatusHandle shareHandle] setShouldFreshOnLianXiRen:@"YES"];
            }
            self.canClickFenZuButton = YES;
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"分组更换失败，请重试" ToView:self];
            self.canClickFenZuButton = YES;
        }];

    }
    
}

#pragma mark - 添加数据源
- (void)addData
{
    // 模拟数据
  //  self.groupArray = [NSMutableArray arrayWithObjects:@"我的好友", @"小学同学", @"初中同学", @"高中同学", @"大学同学", nil];
    // 真实数据
      self.groupArray = [NSMutableArray arrayWithArray:self.fenZuMingZiArray];
    // 被选中的字典
    self.selectDic = [NSMutableDictionary dictionary];
    for (NSString *key in self.groupArray) {
        if ([key isEqualToString:self.selectedGroupName]) {
            [self.selectDic setValue:@"YES" forKey:key];
            self.selectGroupName = key;
        } else {
            [self.selectDic setValue:@"NO" forKey:key];
        }
        
    }

    
    NSLog(@"self.selectDic = %@", self.selectDic);
    
    // 初始化选中小组的名字
    self.selectGroupName = nil;
    
    // 布局
    [self addMySubview];

   
}

#pragma mark - 需要在本页请求分组数据
- (void)shouldQingQiuFenZuData
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    // 获取当前用户的分组列表
    NSString *fenZuListUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWFriendLieBiao, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:fenZuListUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        
        self.fenZuNameArray = [NSMutableArray array];
        self.fenZuNameDuiYingIDDic = [NSMutableDictionary dictionary];
        NSArray *friendGroupArray = [responseObject valueForKey:@"friend_groups"];
        for (NSDictionary *tempDic in friendGroupArray) {
            NSArray *membersArray = [tempDic valueForKey:@"members"];
            for (NSDictionary *userDic in membersArray) {
                if ([[userDic valueForKey:@"user_id"] isEqualToString:self.friend_id]) {
                    // 说明是本人
                    self.selectedGroupName = [tempDic valueForKey:@"name"];
                }
            }
            [self.fenZuNameArray addObject:[tempDic valueForKey:@"name"]];
            [self.fenZuNameDuiYingIDDic setValue:[NSString stringWithFormat:@"%@", [tempDic valueForKey:@"id"]] forKey:[tempDic valueForKey:@"name"]];
        }
        
        self.groupArray = [NSMutableArray arrayWithArray:self.fenZuNameArray];
        self.selectDic = [NSMutableDictionary dictionary];
        for (NSString *key in self.groupArray) {
            if ([key isEqualToString:self.selectedGroupName]) {
                [self.selectDic setValue:@"YES" forKey:key];
                self.selectGroupName = key;
            } else {
                [self.selectDic setValue:@"NO" forKey:key];
            }
        }
        NSLog(@"self.selectDic = %@", self.selectDic);
        
        // 初始化选中小组的名字
        self.selectGroupName = nil;
        
        // 布局
        [self addMySubview];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"用户分组列表获取失败，请返回上一页重新进入" ToView:self];
    }];
    
   

}

#pragma mark - 布局
- (void)addMySubview
{
    self.groupTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, (kScreenHeight - 64) * kAdjustParamater) style:UITableViewStylePlain];
    self.groupTableView.backgroundColor = [UIColor whiteColor];
    self.groupTableView.dataSource = self;
    self.groupTableView.delegate = self;
    [self.view addSubview:_groupTableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.groupArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"selectGroup";
    SelectGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SelectGroupTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *key = self.groupArray[indexPath.row];
    cell.groupNameLabel.text = key;
    // 获取是否点击
    cell.isSelect = [self.selectDic valueForKey:key];
    NSLog(@"%@",[self.selectDic valueForKey:key]);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSString *key = self.groupArray[indexPath.row];
    // 先将字典里面全部改为未选中状态
    for (int i = 0; i < self.groupArray.count; i++) {
        NSString *tempKey = self.groupArray[i];
        [self.selectDic setValue:@"NO" forKey:tempKey];
    }
    // 选中当前
    [self.selectDic setValue:@"YES" forKey:key];
    self.selectGroupName = key;
    [self.groupTableView reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
